import Taro from "@tarojs/taro"
import {H5Config} from './server.interface'
import {newHttp} from "./request";
import {
  ADD_SHARE_VOLUME,
  H5_GET_WX_SIGN,
  ROOKIEGUID_TASK_RECORD,
  UPDATE_USER_SHARE_DATE,
  IDENTITY_IS_SELLER
} from "../constants/api";
import {http} from "./http";
import {user} from "./user.service";

class H5WxJsSdk {
  configData = {
    debug: false,
    openTagList: ['wx-open-launch-weapp'], // 填入打开小程序的开放标签名
    jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage', 'updateAppMessageShareData', 'updateTimelineShareData', 'chooseImage', 'uploadImage', 'chooseWXPay', 'openLocation', 'getLocation', 'hideMenuItems', 'showMenuItems', 'hideAllNonBaseMenuItem', 'showAllNonBaseMenuItem', 'scanQRCode', 'downloadImage']
  }
  menuList = ['menuItem:share:appMessage', 'menuItem:share:timeline', 'menuItem:favorite', 'menuItem:editTag', 'menuItem:delete', 'menuItem:copyUrl', 'menuItem:originPage', 'menuItem:openWithQQBrowser', 'menuItem:openWithSafari', 'menuItem:share:email', 'menuItem:share:brand', 'menuItem:share:qq', 'menuItem:share:weiboApp', 'menuItem:share:facebook', 'menuItem:share:QZone']

  isWeiXin() {
    const ua = window.navigator.userAgent.toLowerCase();
    if (process.env.P_ENV === 'lx') {
      return false
    }
    return ua.match(/MicroMessenger/i) == 'micromessenger'
  }

  async hideCopyUrl() {
    if (!this.isWeiXin()) {
      return;
    }
    wx.ready(function () {
      wx.hideMenuItems(['menuItem:copyUrl']);
    });
  }

  async getConfig() {
    if (!this.isWeiXin()) {
      return;
    }
    const uInfo = Taro.getStorageSync('user') || ''
    if (!uInfo || (uInfo && !uInfo.pkey)) {
      return false
    }
    const menuList = this.menuList
    const href = window.location.href
    const config = await newHttp.catchGet<H5Config>(H5_GET_WX_SIGN, {referer: encodeURI(decodeURI(href))})
    if (config) {
      this.configData = {...this.configData, ...config}
      wx.config(this.configData);
    }
    wx.ready(function () {
      wx.hideMenuItems({
        menuList,// 要隐藏的菜单项，只能隐藏“传播类”和“保护类”按钮，所有menu项见附录3
      });
    });
    wx.error(function(res){
      console.log(res)
    });
  }

  async share(data) {
    if (!this.isWeiXin()) {
      return
    }
    const userInfo = Taro.getStorageSync('user');
    let _title = '';
    let _link = '';
    if (userInfo && process.env.DISTINGUISH_IDENTITY) {
      const identityIsSeller = await http.get(IDENTITY_IS_SELLER, {})
      if (identityIsSeller && identityIsSeller.isSeller) {
        _title = '[分享]';
      }
    }
    const {title = '', desc = '', link = '', imgUrl = '', isProduct = false, uuid = '', category = 0} = data
    if (link) {
      if (process.env.P_ENV === 'kd') {
        _link = link.replace('http://', 'https://')
      } else {
        _link = link
      }
      let mpkey = ''
      const uInfo = Taro.getStorageSync('user') || ''
      if (uInfo && uInfo.mpkey && uInfo.mpkey !== 'undefined') {
        mpkey = uInfo.mpkey
      }
      const flag = link.includes('?')
      if (mpkey) {
        _link += `${flag ? '&' : '?'}mpkey=${mpkey}`
      }
    }
    wx.ready(function () {
      /* , 'menuItem:copyUrl' */
      wx.showMenuItems({
        menuList: ['menuItem:share:appMessage', 'menuItem:share:timeline', 'menuItem:favorite'] // 要显示的菜单项，所有menu项见附录3
      });
      _title = _title + title;
      wx.updateAppMessageShareData({
        title: _title, // 分享标题
        desc, // 分享描述
        link: _link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
        imgUrl, // 分享图标
        success: async function () {
          // 设置成功
          if (process.env.TARO_ENV !== 'tt') {
            http.post(UPDATE_USER_SHARE_DATE, {})
          }
          if (isProduct) {
            await http.get(ADD_SHARE_VOLUME, {category, uuid})
          }
        },
        fail: err => {
          console.log(err)
          /* 出现类似于 {"errMsg":"updateAppMessageShareData:fail, the permission value is offline verifying"} 的错误 原因可能是因为 “微信测试号，非正式的公共号” */
        }
      })
      wx.onMenuShareAppMessage({
        title: _title, // 分享标题
        desc, // 分享描述
        link: _link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
        imgUrl, // 分享图标
        success: async function () {
          console.log('onMenuShareAppMessage')
        },
        fail: err => {
          console.log(err)
          /* 出现类似于 {"errMsg":"updateAppMessageShareData:fail, the permission value is offline verifying"} 的错误 原因可能是因为 “微信测试号，非正式的公共号” */
        }
      })
      wx.updateTimelineShareData({
        title: _title, // 分享标题
        link: _link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
        imgUrl, // 分享图标
        success: async function () {
          // 设置成功
          // await if (process.env.TARO_ENV !== 'tt') {
          // http.post(UPDATE_USER_SHARE_DATE, {})
          // }
          if (isProduct) {
            user.checkLogin().then(isLogin => {
              if (isLogin) {
                http.HPost(ROOKIEGUID_TASK_RECORD, {remark: "朋友圈"})
              }
            })
          }
        }
      })
    });
  }

  async chooseImage(count, callback, big = '') {
    if (!this.isWeiXin()) {
      return;
    }
    wx.ready(function () {
        wx.chooseImage({
          count, // 默认9
          sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
          sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
          success: function (res) {
            let localIds = res.localIds[0]; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片\
            if (big == 'big') {
              localIds = res.localIds
            }
            callback(localIds)
          }, fail(res: any) {
            console.log('res', res)
          }
        });
    })
    wx.error((res)=>{
      console.log('wx.error', res)
    })
  }

  async wxuploadImage(e, callback) {
    if (!this.isWeiXin()) {
      return;
    }
    wx.uploadImage({
      localId: e, // 需要上传的图片的本地ID，由chooseImage接口获得
      isShowProgressTips: 1, // 默认为1，显示进度提示
      success: function (res) {
        const mediaId = res.serverId;
        callback(mediaId)
      },
      fail: function (error) {
        console.log('error', error)
      }
    });
  }

  async openLocation(latitude, longitude, name?: string, address?: string) {
    if (!this.isWeiXin()) {
      return;
    }
    wx.ready(function () {
      wx.openLocation({
        latitude, // 纬度，浮点数，范围为90 ~ -90
        longitude, // 经度，浮点数，范围为180 ~ -180。
        name, // 位置名
        address, // 地址详情说明
        scale: 14, // 地图缩放级别,整型值,范围从1~28。默认为最大
        infoUrl: '' // 在查看位置界面底部显示的超链接,可点击跳转
      });
    });

  }

  async getLocation(callback, type = 'gcj02') {
    if (process.env.P_ENV === 'lx') {
      ls.location((res) => {
        if (res && res.code === 200) {
          callback(res.data)
        }
      })
      return false
    } else {
      if (!this.isWeiXin()) {
        return;
      }
      wx.ready(function () {
        wx.getLocation({
          type, // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
          success: function (res) {
            console.log('wx.getLocation',res)
            callback(res)
          },
          cancel: function (res) {
            console.log('查看附件机器，首先要授权位置信息')
            const pathname = window.location.pathname
            if (pathname === '/movie/index') {
              Taro.showModal({
                title: '定位服务未开启',
                content: '请在“设置->应用权限”中打开微信的位置权限',
                success: () => {
                  Taro.navigateBack({ delta: 1 })
                },
                fail: () => {
                  Taro.navigateBack({ delta: 1 })
                }
              })
            }
            callback(null)
          },
          fail: function (res) {
            console.info('ready getLocation fail=' + JSON.stringify(res))
            if (JSON.stringify(res).includes('getLocation:gps closed') && window.location.pathname === '/movie/index') {
              Taro.showModal({
                title: '定位服务未开启',
                content: '请在“设置->应用权限”中打开微信的位置权限',
                success: () => {
                  Taro.navigateBack({ delta: 1 })
                },
                fail: () => {
                  Taro.navigateBack({ delta: 1 })
                }
              })
            }
            if (res.errMsg === 'getLocation:fail') {
              Taro.showModal({
                title: '定位服务未开启',
                content: '请在“设置->应用权限”中打开微信的位置权限',
                complete: () => {
                  callback(null)
                }
              })
              return
            }
            callback(null)
          }
        });
      })
    }
  }

  async scanQRCode(callback) {
    if (!this.isWeiXin()) {
      return;
    }
    wx.scanQRCode({
      needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
      scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码，默认二者都有
      success: function (res) {
        setTimeout(() => {
          callback(res)
        }, 100)
      }
    });
  }

  async downloadImage(callback, url) {
    if (!this.isWeiXin()) {
      return;
    }
    wx.downloadImage({
      serverId: url, // 需要下载的图片的服务器端ID，由uploadImage接口获得
      isShowProgressTips: 1,// 默认为1，显示进度提示
      success: function (res) {
        callback(res)
      }
    });
  }

  async chooseWXPay(data, callback, errorFn) {
    if (!this.isWeiXin()) {
      return;
    }
    WeixinJSBridge.invoke(
      'getBrandWCPayRequest', {
        ...data
      },
      function (res) {
        if (res.err_msg == "get_brand_wcpay_request:ok") {
          callback(res)
        } else {
          console.log('chooseWXPay:res', res)
          errorFn(res)
        }
      });
  }
}

export const h5Wx = new H5WxJsSdk()
